package com.webserver.core;

import com.webserver.controller.UserController;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;

public class DispatcherServlet {
    private static File root;
    private static File staticDir;

    static {
        try {
            root = new File(DispatcherServlet.class.getClassLoader()
            .getResource(".").toURI());
            staticDir = new File(root,"static");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void service(HttpServletRequest request , HttpServletResponse response) {
        String path = request.getRequestURI();
        System.out.println("请求路径:" + path);

        if ("/myweb/reg".equals(path)) {
            UserController controller = new UserController();
            controller.reg(request, response);
        }else if ("/myweb/login".equals(path)){
            UserController controller = new UserController();
            controller.login(request,response);
        } else {

            File file = new File(staticDir, "/myweb/index.html");
            if (file.isFile()) {
                response.setContentFile(file);
            } else {
                file = new File(staticDir, "/root/404.html");
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                response.setContentFile(file);
            }
        }
    }
}
